package com.example.web;

import com.example.pojo.Book;
import com.example.pojo.Page;
import com.example.service.BookService;
import com.example.service.impl.BookServiceImpl;
import com.example.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ClientBookServlet" ,value = "/client/ClientBookServlet")
public class ClientBookServlet extends BaseServlet{
    private BookService bookService = new BookServiceImpl();
    /**
     * 处理分页功能
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数pageNo,pageSize
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //2.调用bookService.page(pageNo,pageSize);Page对象
        Page<Book> page = bookService.page(pageNo,pageSize);
        page.setUrl("client/ClientBookServlet?action=page");
        //3.保存Page对象到Request域中
        request.setAttribute("page", page);
        //4.请求转发到pages/manager/book_manger.jsp页面
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request, response);
    }


    /**
     * 查询价格区间
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void pageByPrice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数pageNo,pageSize
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = WebUtils.parseInt(request.getParameter("min"),0);
        int max = WebUtils.parseInt(request.getParameter("max"),Integer.MAX_VALUE);
        //2.调用bookService.page(pageNo,pageSize);Page对象
        Page<Book> page = bookService.pageByPrice(pageNo,pageSize,min,max);
        StringBuilder sb = new StringBuilder("client/ClientBookServlet?action=pageByPrice");
        //如果有最小这个参数，追加地址栏
        if(request.getParameter("min") != null){
            sb.append("&min=").append(request.getParameter("min"));
        }
        //如果有最大这个参数，追加地址栏
        if(request.getParameter("max") != null){
            sb.append("&max=").append(request.getParameter("max"));
        }
        page.setUrl(sb.toString());
        //3.保存Page对象到Request域中
        request.setAttribute("page", page);
        //4.请求转发到pages/manager/book_manger.jsp页面
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request, response);
    }

}
